package cn.iocoder.yudao.module.enterprise.service.emissionsource;

import cn.iocoder.yudao.module.carbon.api.gas.GasApi;
import cn.iocoder.yudao.module.carbon.api.gas.dto.GasRespDTO;
import cn.iocoder.yudao.module.carbon.api.gwp.GwpApi;
import cn.iocoder.yudao.module.carbon.api.gwp.dto.GwpListReqDTO;
import cn.iocoder.yudao.module.carbon.api.gwp.dto.GwpRespDTO;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.emissionsource.EmissionGaseDO;
import cn.iocoder.yudao.module.enterprise.dal.mysql.emissionsource.EmissionGaseMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;

/**
 * 排放源的温室气体 Service 实现类
 *
 * @author StevenShen
 */
@Service
@Validated
public class EmissionGaseServiceImpl implements EmissionGaseService {

    @Resource
    private EmissionGaseMapper emissionGaseMapper;
    @Resource
    private GasApi gasApi;
    @Resource
    private GwpApi gwpApi;

    @Override
    public Map<Integer, Double> getEmissionGaseMap(Long emissionId, Double dataValue, Integer gwp) {
        List<EmissionGaseDO> emissionGaseList = emissionGaseMapper.selectListByEmissionId(emissionId);
        List<Long> gasIds = convertList(emissionGaseList, EmissionGaseDO::getGaseId);
        Map<Long, GasRespDTO> gasMap = gasApi.getGasMap(gasIds).getCheckedData();

        Map<String, Integer> gasIndexMap = new HashMap<>();
        gasIndexMap.put("二氧化碳（CO2）", 0);
        gasIndexMap.put("甲烷（CH4）", 1);
        gasIndexMap.put("氧化亚氮（N2O）", 2);
        gasIndexMap.put("氢氟碳化物（HFCs）", 3);
        gasIndexMap.put("全氟化碳（PFCs）", 4);
        gasIndexMap.put("六氟化硫（SF6）", 5);
        gasIndexMap.put("三氟化氮（NF3）", 6);

        // 获取GWP信息
        List<GwpRespDTO> gwpList = gwpApi.getGwpList(new GwpListReqDTO().setReportVersion(gwp)).getCheckedData();

        Map<Integer, Double> resultMap = new HashMap<>();
        resultMap.put(0, 0D);
        resultMap.put(1, 0D);
        resultMap.put(2, 0D);
        resultMap.put(3, 0D);
        resultMap.put(4, 0D);
        resultMap.put(5, 0D);
        resultMap.put(6, 0D);

        emissionGaseList.forEach(e -> {
            GasRespDTO gas = gasMap.get(e.getGaseId());
            Integer gasIndex = gasIndexMap.get(gas.getCategory());
            double count = resultMap.containsKey(gasIndex) ? resultMap.get(gasIndex) : 0;
            // 获取该温室气体的GWP值
            Optional<GwpRespDTO> gwpOptional = gwpList.stream().filter(e2 -> e2.getGaseId().equals(e.getGaseId())).findFirst();
            if (gwpOptional.isPresent()) {
                GwpRespDTO gwpDTO = gwpOptional.get();
                resultMap.put(gasIndex, count + dataValue * e.getValue() * gwpDTO.getGwp());
            }
        });

        return resultMap;
    }

}
